#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unsigned long long res = 0;
    unsigned long long path(TreeNode* root, unsigned long long sum, int targetSum)
    {
        if (root == nullptr)
            return 0;

        unsigned long long ret = 0;
        if (root->val == targetSum - sum) ret = 1;

        unsigned long long left = path(root->left, sum + root->val, targetSum);
        unsigned long long right = path(root->right, sum + root->val, targetSum);

        return ret + left + right;
    }
    void dfs(TreeNode* root, int targetSum)
    {
        if (root == nullptr)
            return;

        res += path(root, 0, targetSum);
        dfs(root->left, targetSum);
        dfs(root->right, targetSum);
    }
    int pathSum(TreeNode* root, int targetSum) {
        dfs(root, targetSum);
        return res;
    }
};

TreeNode* buildTree(vector<int*>& nodes) {
    if (nodes.empty() || nodes[0] == nullptr) return nullptr;

    TreeNode* root = new TreeNode(*nodes[0]);
    queue<TreeNode*> q;
    q.push(root);

    int i = 1;
    while (!q.empty() && i < nodes.size()) {
        TreeNode* current = q.front();
        q.pop();

        if (nodes[i] != nullptr) {
            current->left = new TreeNode(*nodes[i]);
            q.push(current->left);
        }
        i++;

        if (i < nodes.size() && nodes[i] != nullptr) {
            current->right = new TreeNode(*nodes[i]);
            q.push(current->right);
        }
        i++;
    }

    return root;
}
int main()
{
    vector<int*> nodes = { new int(10), new int(5), new int(-3), new int(3), new int(2), nullptr, new int(11), new int(3), new int(-2), nullptr, new int(1) };
    TreeNode* root = buildTree(nodes);

    cout << Solution().pathSum(root, 8);
    return 0;
}